package com.learn.elasticsearchnews.service;

import com.learn.elasticsearchnews.model.NewsModel;
import com.learn.elasticsearchnews.utils.EsUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.unit.Fuzziness;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.FieldSortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class MySearchService {

	public ArrayList<NewsModel> searchSinaNews(String keywords, Integer from, Integer size) throws Exception {
		if (null == from) from = 0;
		if (null == size) size = 10;
		RestHighLevelClient client = EsUtils.getClient();

		String index = "sina_news";
		String field1 = "news_type";
		String field2 = "rich_text";
		MultiMatchQueryBuilder multiMatchQueryBuilder = QueryBuilders.multiMatchQuery(keywords, field1, field2)
				.fuzziness(Fuzziness.AUTO);
		HighlightBuilder highlightBuilder = new HighlightBuilder()
				.preTags("<span style=\"color:red\">")
				.postTags("</span>")
				.field(field1)
				.field(field2);

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
		searchSourceBuilder.query(multiMatchQueryBuilder);
		searchSourceBuilder.sort(new FieldSortBuilder("id").order(SortOrder.DESC));
		searchSourceBuilder.from(from);
		searchSourceBuilder.size(size);
		searchSourceBuilder.timeout(new TimeValue(5, TimeUnit.SECONDS));
		searchSourceBuilder.highlighter(highlightBuilder);

		SearchRequest searchRequest = new SearchRequest();
		searchRequest.indices(index);
		searchRequest.source(searchSourceBuilder);

		SearchResponse searchResponse = client.search(searchRequest, RequestOptions.DEFAULT);
		ArrayList<NewsModel> resultList = new ArrayList<>();
		if(searchResponse.status() == RestStatus.OK) {
			SearchHits searchHits = searchResponse.getHits();
			for (SearchHit hit : searchHits) {
				Map<String, Object> resMap =hit.getSourceAsMap();
				Map<String, NewsModel> newsMap = new HashMap<>();
				NewsModel news = new NewsModel(
						Integer.valueOf(resMap.get("id").toString()),
						resMap.get("news_type").toString(),
						resMap.get("rich_text").toString(),
						resMap.get("create_time").toString());
				resultList.add(news);
			}
		}
		return resultList;
	}

}
